// pages/kangyang/index.js
const app = getApp()
const tabData = {
  1: { name: '机构康养', api: 'Kangyang/kangyanglists','type':1},
  2: { name: '居家康养', api: 'Community/index','type':2 },
  3: { name: '社区养老', api: 'Kangyang/kangyanglists','type':3 }
}

Page({
  data: {
    tabs: [
      { id: 1, name: '机构康养' },
      { id: 2, name: '居家康养' },
      { id: 3, name: '社区养老' }
    ],
    activeTab: 2,
    tagColors: ['#e8f8f0', '#fce4ec', '#f0f4c3'],
    currentList: [],
    page: 1,
    pageSize: 10,
    isLoading: false,
    noMoreData: false,
	type:1,
	communities: [],
	activeIndex: 0 // 默认展开第一条
  },

  onLoad() {
	  let self= this
	  wx.getLocation({
	  	type: 'wgs84',
	  	success(res) {
	  		// 定位成功，获取最近的店，并提示是否切换
	  		//self.main_load(false);
	  		wx.setStorageSync('lng',res.longitude);
	  		wx.setStorageSync('lat',res.latitude);
	  		
	  	},
	  	fail(res) {
	  		console.log("fail");
	  		console.log(res);
	  	}
	  });
	  wx.checkSession({
	  	success() { 
	  		console.log('succ')
	  		app.util.getUserInfo(function (response) {
	  			console.log("==获取当前用户信息1==");
	  			console.log(response);
	  			self.setData({
	  				userInfo: response
	  			});
	  			console.log("==应用初始化：应用配置/应用中用户信息/当前城市信息==");
	  			
	  			setTimeout(function(){
	  				self.loadData(true)
	  			},500)
	  		});
	  	},
	  	fail() { 
			app.util.getUserInfo(function (response) {
				console.log("==获取当前用户信息1==");
				console.log(response);
				self.setData({
					userInfo: response
				});
				console.log("==应用初始化：应用配置/应用中用户信息/当前城市信息==");
				
				setTimeout(function(){
					self.loadData(true)
				},500)
			});
	  	}
	  });
    
  },

  // 切换Tab
  switchTab(e) {
    const tabId = e.currentTarget.dataset.id
    if (this.data.activeTab === tabId) return
    this.setData({ 
      activeTab: tabId,
	  type:tabData[this.data.activeTab].type,
      currentList: [],
      page: 1,
      noMoreData: false
    }, () => this.loadData(true))
  },

  // 加载数据
  async loadData(init = false) {
    if (this.data.noMoreData && !init) return
    this.setData({ isLoading: true })
	let that = this;
	let lng = wx.getStorageSync('lng')
	
	let lat = wx.getStorageSync('lat')
    try {
      app.util.request({
        url: tabData[that.data.activeTab].api,
        data: {
			type:tabData[that.data.activeTab].type,
			is_kangyang:2,
			  page: init ? 1 : that.data.page,
			  pageSize: that.data.pageSize,
			lng:lng,
			lat:lat
        },
		success(res){
			if(tabData[that.data.activeTab].type == 2){
				// that.setData({
				//   currentList: init ? res.data.data.list : [...that.data.currentList, ...res.data.data.list],
				//   page: init ? 2 : that.data.page + 1,
				//   noMoreData: res.data.data.list.length < that.data.pageSize,
				//   isLoading: false
				// })
				var data = res.data.data;
				that.setData({
					communities: data
				});
			}else{
				that.setData({
				  currentList: init ? res.data.data.kangyang : [...that.data.currentList, ...res.data.data.kangyang],
				  page: init ? 2 : that.data.page + 1,
				  noMoreData: res.data.data.kangyang.length < that.data.pageSize,
				  isLoading: false
				})
			}
			
		}
      })

      
    } catch (error) {
      this.setData({ isLoading: false })
      wx.showToast({ title: '加载失败', icon: 'none' })
    }
  },
// 切换社区展开状态
  toggleCommunity(e) {
    const index = e.currentTarget.dataset.index;
    if (this.data.activeIndex === index) {
      this.setData({ activeIndex: -1 }); // 点击已展开的则关闭
    } else {
      this.setData({ activeIndex: index });
    }
  },
	goCommunity(e){
		const id = e.currentTarget.dataset.id;
		wx.navigateTo({
			url:'../communitydoctor/detail?id='+id
		});
	},
  // 预约套餐
  makeAppointment(e) {
    const package1 = e.currentTarget.dataset.package;
	console.log(package1)
	
		wx.setStorageSync("selectPackage",package1)
		wx.navigateTo({
		  url: `/vp_pz/pages/kangyang/jujiadetail?id=`+package1
		})
  },
// 导航到社区
  navigateToCommunity(e) {
    const { latitude, longitude, name } = e.currentTarget.dataset;
    
    wx.showActionSheet({
      itemList: ['腾讯地图', '高德地图'],
      success: (res) => {
        const mapApps = ['qqmap', 'amap'];
        const selectedApp = mapApps[res.tapIndex];
        
        wx.openLocation({
          latitude: parseFloat(latitude),
          longitude: parseFloat(longitude),
          name: name,
          address: name,
          scale: 18,
          success: () => {
            console.log('打开地图成功');
          },
          fail: (err) => {
            console.error('打开地图失败', err);
            wx.showToast({
              title: '打开地图失败',
              icon: 'none'
            });
          }
        });
      },
      fail: (err) => {
        console.error('用户取消选择', err);
      }
    });
  },
  // 跳转详情
  navigateToDetail(e) {
    const id = e.currentTarget.dataset.id
	console.log('eee')
	console.log(tabData[this.data.activeTab].type)
	wx.navigateTo({
	  url: `/vp_pz/pages/kangyang/detail?id=${id}`
	})
  }
})